package cn.wolfcode.trip.app.controller;

import cn.wolfcode.trip.base.domain.Travel;
import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.query.TravelQueryObject;
import cn.wolfcode.trip.base.service.ITravelService;
import cn.wolfcode.trip.base.service.IUserService;
import cn.wolfcode.trip.base.util.JSONResult;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import sun.util.resources.ga.LocaleNames_ga;

/**
 * 注册用户的资源控制器
 */
@RestController
@RequestMapping("users")
public class UserController {

    @Autowired
    private IUserService userService;

    @Autowired
    private ITravelService travelService;

    @RequestMapping(method = RequestMethod.POST)
    public JSONResult register(User user){
        JSONResult result = new JSONResult();

        try {
            userService.register(user);
        } catch (Exception e) {
            e.printStackTrace();
            result.mark(e.getMessage());
        }

        return result;
    }

    @RequestMapping(method = RequestMethod.PUT)
    public JSONResult update(User user){
        JSONResult result = new JSONResult();

        try {
            userService.update(user);
            result.setResult(user);
        } catch (Exception e) {
            e.printStackTrace();
            result.mark(e.getMessage());
        }

        return result;
    }

    /**
     * 查询指定用户的游记列表
     * @param qo
     * @return
     */
    @RequestMapping(value = "/{authorId}/travels",method = RequestMethod.GET)
    public PageInfo query(TravelQueryObject qo){

        qo.setOrderBy("t.createTime desc");
        return travelService.querForList(qo);
    }

    /**
     * 新增游记
     * @param
     *
     */
    @RequestMapping(value = "/{author.id}/travels",method = RequestMethod.POST)
    public JSONResult query(Travel travel){
        JSONResult result = new JSONResult();
        try {
            travelService.save(travel);
        } catch (Exception e) {
            e.printStackTrace();
            result.mark(e.getMessage());
        }
        return result;
    }

    /**
     * 获取指定id的user信息
     * id:用户的id
     */
    @RequestMapping(value = "/{id}",method = RequestMethod.GET)
    public User getUserById(@PathVariable Long id){
        return userService.getUserById(id);
    }
}